<template>
  <!-- 退款审批 -->
  <div class="refund-approval">
    <Return />
    <div class="refund-approval-header" :style="{ height: headerHeight + 'px' }">
      <div class="refund-approval-header-bottom">
        <template v-for="(item, index) in refundTabs" :key="item.title">
          <div class="refund-approval-header-bottom-item">
            <div class="item-box" :class="{ 'item-box-active': index === activeIndex }" @click="handleTabChange(index)">
              <div>{{ item.title }}</div>
            </div>
          </div>
        </template>
      </div>
    </div>

    <scroll-view class="refund-approval-content" scroll-y="true" :style="{ height: contentHeight + 'px' }"
      @scrolltolower="loadMore" @refresherrefresh="onRefresh" :refresher-enabled="true" :refresher-triggered="refreshing">

      <!-- 加载中 -->
      <div v-if="loading && refundList.length === 0" class="loading-container">
        <div class="loading">加载中...</div>
      </div>

      <!-- 空状态 -->
      <div v-else-if="refundList.length === 0" class="empty-container">
        <div class="empty-text">暂无退款申请</div>
      </div>

      <!-- 退款列表 -->
      <template v-else>
        <div v-for="(refund, index) in refundList" :key="refund.id" @click="handleRefundDetail(refund)" class="refund-approval-content-item">
          <!-- 订单基本信息 -->
          <div class="refund-approval-content-item-header">
            <div class="refund-approval-content-item-header-title">
              <div class="refund-approval-content-item-header-title-top">
                <span class="order-no">订单号：{{ refund.orderNo }}</span>
                <span
                  class="status-tag"
                  :class="{
                    'status-pending': refund.shopApprovalStatus == '0',
                    'status-approved': refund.shopApprovalStatus == '1',
                    'status-rejected': refund.shopApprovalStatus == '2'
                  }"
                >
                  {{ getStatusText(refund.shopApprovalStatus) }}
                </span>
              </div>
              <div class="refund-approval-content-item-header-title-button">
                <span class="apply-time">申请时间：{{ refund.createTime }}</span>
              </div>
            </div>
          </div>

          <div class="page-line"></div>

          <!-- 用户信息 -->
          <div class="user-info">
            <div class="user-info-item">
              <div class="user-info-label">联系人</div>
              <div class="user-info-value">{{ refund.contactName || '未提供' }}</div>
            </div>
            <div class="user-info-item">
              <div class="user-info-label">联系电话</div>
              <div class="user-info-value">{{ refund.contactPhone || '未提供' }}</div>
            </div>
          </div>

          <div class="page-line"></div>

          <!-- 退款详情 -->
          <div class="refund-details">
            <div class="detail-item">
              <div class="detail-label">退款金额</div>
              <div class="detail-value refund-amount">¥{{ refund.refundAmount }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">退款原因</div>
              <div class="detail-value">{{ refund.refundCause }}</div>
            </div>
            <div class="detail-item">
              <div class="detail-label">申请时间</div>
              <div class="detail-value">{{ refund.createTime }}</div>
            </div>
          </div>

          <!-- 退款凭证图片 -->
          <div class="refund-images" v-if="refund.refundImg">
            <div class="images-title">退款凭证</div>
            <div class="images-list">
              <image v-for="(img, imgIndex) in getRefundImages(refund.refundImg)" :key="imgIndex"
                :src="img" mode="aspectFill" @click="previewImage(img, getRefundImages(refund.refundImg))"/>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="order-actions" v-if="refund.status === '0'">
            <div class="action-buttons">
              <div class="action-btn secondary" @click="handleRefund(refund, 'reject')">
                拒绝退款
              </div>
              <div class="action-btn primary" @click="handleRefund(refund, 'approve')">
                同意退款
              </div>
            </div>
          </div>
        </div>
      </template>

      <!-- 加载更多 -->
      <div v-if="loadingMore" class="loading-more">
        <div class="loading-text">加载更多...</div>
      </div>
    </scroll-view>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import Return from '@/components/Return.vue'

const headerHeight = ref(110)
const contentHeight = ref(600)
const activeIndex = ref(0)
const loading = ref(false)
const loadingMore = ref(false)
const refreshing = ref(false)
const page = ref(1)
const hasMore = ref(true)

// 退款状态tabs
const refundTabs = ref([
  { title: '待处理', status: '0' },
  { title: '已同意', status: '1' },
  { title: '已拒绝', status: '2' }
])

// 退款列表数据
const refundList = ref([])

// 状态文字映射
const statusTextMap = {
  '0': '待处理',
  '1': '已同意',
  '2': '已拒绝'
}

// 获取状态文本
const getStatusText = (status) => {
  return statusTextMap[status] || '未知状态'
}

// 计算内容区高度
const calcContentHeight = () => {
  const systemInfo = uni.getSystemInfoSync()
  // #ifdef MP-WEIXIN
  const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
  headerHeight.value = menuButtonInfo.bottom + 54
  // #endif
  contentHeight.value = systemInfo.windowHeight - headerHeight.value
}
const shopId = ref('')
onLoad((options) => {
  console.log(options, 'options');
  shopId.value = options.shopId
})
onShow(() => {
  fetchRefundList(true)
})
// 获取退款订单列表
const fetchRefundList = async (isRefresh = false) => {
  if (loading.value && !isRefresh) return

  if (isRefresh) {
    page.value = 1
    hasMore.value = true
  }

  if (!hasMore.value) return

  loading.value = true
  loadingMore.value = !isRefresh

  try {
    // 根据当前标签类型选择不同的接口
    const currentTab = refundTabs.value[activeIndex.value];

    const params = {
      page: page.value,
      limit: 10,
      shopId: shopId.value,
      shopApprovalStatus: currentTab.status,
    }

    const { status, data } = await Fetch('shopping/refundRequest/shopRequestList', {
      method: 'GET',
      data: params
    })

    console.log(status, data, 'status, data ',status === 200 && data.code === 200);

    if (status === 200 && data.code === 200) {
      const newOrders = data.rows || []

      if (isRefresh) {
        refundList.value = newOrders
      } else {
        refundList.value.push(...newOrders)
      }

      hasMore.value = newOrders.length === 10
      page.value++
    } else {
      uni.showToast({
        title: data?.msg || '获取订单失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取订单失败:', error)
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  } finally {
    loading.value = false
    loadingMore.value = false
    refreshing.value = false
  }
}

const handleRefundDetail = (refund) => {
  uni.navigateTo({
    url: `/pages/RefundDetail?orderId=${refund.orderId}&refundId=${refund.refundRequestId}`
  })
}

// 处理退款
const handleRefund = async (refund, action) => {
  const isApprove = action === 'approve'
  uni.showModal({
    title: '确认提示',
    content: isApprove ? '确认同意此退款申请？' : '确认拒绝此退款申请？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await Fetch('shopping/refund/process', {
            method: 'POST',
            data: {
              refundId: refund.id,
              status: isApprove ? '1' : '2'
            }
          })

          if (result.data.code === 200) {
            uni.showToast({
              title: isApprove ? '已同意退款' : '已拒绝退款',
              icon: 'success'
            })
            fetchRefundList(true)
          }
        } catch (error) {
          uni.showToast({
            title: '操作失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 图片预览
const previewImage = (current, urls) => {
  uni.previewImage({
    current,
    urls
  })
}

// 获取退款凭证图片
const getRefundImages = (imgUrl) => {
  if (imgUrl) {
    return imgUrl.split(',').map(url => url.trim());
  }
  return [];
};

// Tab切换
const handleTabChange = (index) => {
  if (activeIndex.value === index) return
  activeIndex.value = index
  fetchRefundList(true)
}

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loadingMore.value) {
    loadingMore.value = true
    fetchRefundList()
  }
}

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true
  fetchRefundList(true)
}

onMounted(() => {
  calcContentHeight()
})
</script>

<style lang="scss" scoped>
.refund-approval {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;

  .refund-approval-header {
    background: #FFFFFF;
    position: relative;
    margin-bottom: 20rpx;
    z-index: 2;

    .refund-approval-header-bottom {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 96rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .refund-approval-header-bottom-item {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;

        .item-box {
          font-weight: bold;
          font-size: 28rpx;
          color: #191919;
          line-height: 40rpx;
          text-align: center;
          cursor: pointer;

          &.item-box-active {
            position: relative;

            &::after {
              content: '';
              display: block;
              width: 40rpx;
              height: 8rpx;
              background: #F9DC40;
              border-radius: 4rpx;
              position: absolute;
              bottom: -10rpx;
              left: 50%;
              transform: translateX(-50%);
            }
          }
        }
      }
    }
  }

  .refund-approval-content {
    flex: 1;
    overflow: auto;
    padding: 0 20rpx;
    box-sizing: border-box;

    .refund-approval-content-item {
      background: #FFFFFF;
      border-radius: 20rpx;
      padding: 24rpx;
      margin-bottom: 20rpx;

      .refund-approval-content-item-header {
        display: flex;
        align-items: center;
        margin-bottom: 32rpx;

        image {
          width: 76rpx;
          height: 76rpx;
          border-radius: 16rpx;
          margin-right: 16rpx;
        }

        .refund-approval-content-item-header-title {
          flex: 1;

          .refund-approval-content-item-header-title-top {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .order-no {
              font-size: 30rpx;
              color: #000000;
              font-weight: bold;
            }

            .status-tag {
              font-weight: 400;
              font-size: 24rpx;
              line-height: 32rpx;
              text-align: center;
              padding: 6rpx 12rpx;
              border-radius: 16rpx;
              margin-left: 20rpx;

              // 待处理状态 - 橙色
              &.status-pending {
                background: #FFF7E6;
                color: #FA8C16;
                border: 1rpx solid #FFD591;
              }

              // 已同意状态 - 绿色
              &.status-approved {
                background: #F6FFED;
                color: #52C41A;
                border: 1rpx solid #B7EB8F;
              }

              // 已拒绝状态 - 红色
              &.status-rejected {
                background: #FFF2F0;
                color: #FF4D4F;
                border: 1rpx solid #FFCCC7;
              }
            }
          }

          .refund-approval-content-item-header-title-button {
            display: flex;
            color: #A0A0A0;
            font-size: 22rpx;
            margin-top: 10rpx;
          }
        }
      }

      .user-info {
        background: #F8F8F8;
        border-radius: 16rpx;
        padding: 20rpx;
        margin: 20rpx 0;

        .user-info-item {
          display: flex;
          justify-content: space-between;
          margin-bottom: 10rpx;

          &:last-child {
            margin-bottom: 0;
          }

          .user-info-label {
            color: #666;
            font-size: 26rpx;
          }

          .user-info-value {
            color: #191919;
            font-size: 26rpx;
            font-weight: 500;
          }
        }
      }

      .refund-details {
        background: #F8F8F8;
        border-radius: 16rpx;
        padding: 20rpx;
        margin: 20rpx 0;

        .detail-item {
          display: flex;
          justify-content: space-between;
          margin-bottom: 10rpx;

          .detail-label {
            color: #666;
            font-size: 26rpx;
          }

          .detail-value {
            color: #191919;
            font-size: 26rpx;
          }
        }
      }

      .refund-images {
        margin-top: 20rpx;

        .images-title {
          font-size: 26rpx;
          color: #666;
          margin-bottom: 16rpx;
        }

        .images-list {
          display: flex;
          flex-wrap: wrap;
          gap: 16rpx;

          image {
            width: 180rpx;
            height: 180rpx;
            border-radius: 8rpx;
          }
        }
      }

      .order-actions {
        margin-top: 30rpx;

        .action-buttons {
          display: flex;
          justify-content: flex-end;
          gap: 20rpx;

          .action-btn {
            padding: 16rpx 30rpx;
            border-radius: 30rpx;
            font-size: 28rpx;
            font-weight: bold;

            &.primary {
              background-color: #F9DC40;
              color: #191919;
            }

            &.secondary {
              background-color: #E0E0E0;
              color: #191919;
            }
          }
        }
      }
    }
  }
}

.page-line {
  height: 1rpx;
  background: #F5F5F5;
  margin: 20rpx 0;
}

.loading-more {
  text-align: center;
  padding: 20rpx 0;
  color: #999;
  font-size: 24rpx;
}
</style>
